# rest_framework
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
from rest_framework.permissions import AllowAny
from rest_framework.decorators import api_view
from rest_framework import generics
from django.contrib.auth.hashers import make_password

from apps.user.serializers import UserRegisterSerializer
# utils and app
from utils.rest_framework_util.response import rtn_error_info, rtn_success_info, rtn_warning_info
from utils.rest_framework_util.error_info_list import ErrorInfo
from utils.settings.log_config import logger
from utils.utils import check_register_info
from apps.user.models import User
from base.celery_tasks import celery_task


class UserLoginView(TokenObtainPairView):
    """
    用户登录接口
    """
    permission_classes = ()
    authentication_classes = ()

    def post(self, request, *args, **kwargs):
        password = request.data.get("password", None)
        username = request.data.get("username", None)
        logger.info(f"[REQUEST_PARAMS]username:{username},password:{password}")
        if password is None or username is None:
            return rtn_error_info(f"【WARNING】username or password is empty data.")
        if len(password) < 5:
            return rtn_error_info(f"【ERROR】password error!")
        data = {
            "password": password,
            "username": username
        }
        serializer = self.get_serializer(data=data)
        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            logger.error("TokenERROR")
            return rtn_error_info("【ERROR】Token错误", code=401)
        except InvalidToken as e:
            logger.error("InvalidToken")
            return rtn_error_info("【ERROR】Token无效", code=502)
        except:
            logger.error("【ERROR】Missing Thing")
            return rtn_warning_info(ErrorInfo.LOGIN_ERROR_USERNAME_PASSWORD)
        result = serializer.validated_data
        arco_response = {
            'token': f"{result['access']}"
        }
        return rtn_success_info(arco_response, "用户登录成功")


class UserRegisterView(generics.CreateAPIView):
    """
    用户注册接口
    """
    queryset = User.objects.all()
    serializer_class = UserRegisterSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        serialize = self.get_serializer(data=request.data)
        if serialize.is_valid():
            username = serialize.data['username']
            password = serialize.data['password']
            logger.info(f"[username]:{username}[password]:{password}")
            if username is None or password is None:
                return rtn_warning_info(ErrorInfo.REGISTER_NONE_INFO)
            is_check, result = check_register_info(username, password)
            if not is_check:
                return rtn_error_info(result)
            if User.objects.filter(username=username).count() > 0:
                return rtn_warning_info(ErrorInfo.REGISTER_SAME_USER)  # 当前用户已存在
            user = User.objects.create(username=username, password=make_password(password))
            user.save()
        else:
            return rtn_error_info(msg='当前用户存在或账号密码错误')
        return rtn_success_info(request.data)


@api_view(['GET'])
def get_celery_result(request):
    task_id = request.GET.get('task_id', 'default')
    task_result = celery_task.AsyncResult(task_id)
    if task_result.ready():
        return rtn_success_info({'status': 'Complete', 'result': task_result.get()})
    else:
        return rtn_success_info({'status': 'Pending'})
